/* entity */
import EsTask from '@model/entity/EsTask'
import TaskType from '@model/entity/TaskType'
import Auth from '@model/entity/Auth'
/* methods */
import AllotMapDialogMethods from '@src/modules/task/taskTypes/allot/components/AllotMapDialog/AllotMapDialogMethods'
/* service */
import { allotTaskJump, allowModifyPlanTimeJudgeHandler } from '@service/TaskService'
/* util */
import { fmt_address, fmt_datetime } from '@src/filter/fmt'
import { openTabForCustomerView, openTabForTaskView } from '@src/util/business/openTab'
import { isCalendar } from '@src/util/CalendarUtil'
import { getRootWindowInitData } from '@src/util/window'
import i18n from '@src/locales'
/* service */
import AuthService from '@service/AuthService'
/* vue */
import { VNode } from 'vue'



class AllotMapDialogRender extends AllotMapDialogMethods {
  
  get globalRootWindowInitData() {
    return getRootWindowInitData()
  }
  
  /** 
   * @description 全局登录用户权限
  */
  get globalLoginUserAuth(): Auth {
    return (this.globalRootWindowInitData?.user?.auth || {}) as Auth
  }
  
  get globalIsHaveTaskViewDetailAuth() {
    return AuthService.isHaveTaskViewDetailAuth(this.globalLoginUserAuth)
  }

  get globalIsHaveCustomerViewDetailAuth() {
    return AuthService.isHaveCustomerViewDetailAuth(this.globalLoginUserAuth)
  }
  
  /**
   * @description 渲染指派地图元素
   * @return {VNode}
   */  
  public renderAllotMapElement(): VNode {
    return (this.mapShow && this.currentMapType && <bbx-power-map currentMapType={this.currentMapType}  oninfoWindowFnc={(e)=>this.infoWindowFnc(e)} style='height: 100%' init-setting={{zoom:5}} ref="baseMapContainer"/>)
  }
  
  /**
   * @description 渲染指派地图容器
   * @return {VNode}
   */  
  public renderAllotMapContainer(): VNode {
    return (
      <div class='allot-map-container'>
        { this.renderAllotMapElement() }
        { this.renderAllotMapDialogSide() }
      </div>
    )
  }
  
  /**
   * @description 渲染指派地图侧边栏
   * @return {VNode}
   */  
  public renderAllotMapDialogSide(): VNode {
    return (
      <div class={['allot-map-side', !this.visibleMapSide && 'shut']}>
        <i 
          class={[this.visibleMapSide ? 'icon-right1': 'icon-left1', 'btn-side', 'iconfont']}
          onClick={() => this.toggleVisibleMapSide()}
        >
        </i>
        <div class='side-list-header overHideCon-1'>{i18n.t('task.tip.mapModeTip6')}</div>
        { this.renderAllotMapDialogSideList() }
        <div 
          class='allot-map-footer pointer' 
          onClick={() => this.openBatchAllotDialog()}
        >
          <div class='allot-map-footer-content'>{i18n.t('task.taskTypes.allot.batchAllot')} ({ this.selectedTaskMapData.length || 0}/{this.taskMapData.length || 0})</div>
        </div>
      </div>
    )
  }
  
  /**
   * @description 渲染指派地图侧边栏列表
   * @return {VNode}
   */  
  public renderAllotMapDialogSideList(): VNode {
    return (
      <div ref='AllotMapDialogSideListElement' class='side-list'>
        {this.taskMapData.map((task, index) => this.renderAllotMapDialogSideListItem(task, index))}
        {this.hasNextPage && (
          <div class='side-list-loadmore link-text task-pointer'>
            <span onClick={() => this.debouncedLoadmoreAllotList()}>{i18n.t('common.base.tip.loadMore')}</span>
          </div>
        )}
        {!this.hasNextPage && this.taskMapData.length <= 0 && (
          <div class='side_list_loadmore side_list_empty'>
            {i18n.t('task.tip.allotTaskTip1')}
          </div>
        )}
      </div>
    )
  }
  
  /**
   * @description 渲染指派地图侧边栏列表每一项
   * @return {VNode}
   */  
  public renderAllotMapDialogSideListItem(task: EsTask, index: number): VNode {
    // 联系人电话
    const linkmanPhone: string = task?.linkMan?.phone || ''
    const customerId: string = task?.customerEntity?.id || ''
    const isShowCalendarTime = task.planStartTimeShow || task.planEndTimeShow || false;
    
    return (
      <div
        class={[task.isClick && 'isClick', 'side-list-item', 'pointer']}
        ref={`side_item_${index}`}
        key={`${task.id}_${index}`}
      >
        <div class='side-list-item-content' onClick={() => this.clickListItem(task, index)}>
          <div class={[task.selected && 'selected', 'icon_num']}>{index+1}</div>
          <div class='task-span1'>
            <p
              class={['customer-name', this.globalIsHaveCustomerViewDetailAuth && 'link-text']}
              onClick={() => {
                if (!this.globalIsHaveCustomerViewDetailAuth) return
                openTabForCustomerView(customerId)
              }}
            >{ task?.customerEntity?.name || '' }</p>
            <p>
              {i18n.t('common.form.type.taskNo')}：
              <span
                class={this.globalIsHaveTaskViewDetailAuth && 'link-text'}
                onClick={() => {
                  if (!this.globalIsHaveTaskViewDetailAuth) return
                  openTabForTaskView(task.id)
                }}
              >{ task.taskNo }</span>
            </p>
            <p>{i18n.t('common.task.taskType')}：{ task.templateName }</p>
            <p>{i18n.t('common.base.contact')}：{task?.linkMan?.name || ''}</p>
            <p class='side-item-phone'>
              {i18n.t('common.base.phone')}：{linkmanPhone}
              {linkmanPhone && <biz-call-center-phone phone={linkmanPhone} />}
            </p>
            <p class='item_text'>{i18n.t('common.base.address')}：{ fmt_address(task?.address) }</p>
            { 
              !isCalendar && task.planTime && <p class='side-item-time'>
                {i18n.t('common.form.type.planTime')}：{(task.planTime && fmt_datetime(task.planTime)) || '--'}
                {allowModifyPlanTimeJudgeHandler(task) && (
                  <i class='iconfont icon-bianji1' onClick={(event: Event) => this.openPlanTimeDialog(event, task, index)}></i>
                )}
              </p>
            }
            { isCalendar && isShowCalendarTime && this.renderCalendarTimeDom(task, index) }
          </div>
        </div>
        <div class='side-list-item-info'>
          <el-checkbox value={task.selected} onChange={() => this.toggleMapTaskSelected(index)}></el-checkbox>
        </div>
      </div>
    )
  }

  public renderCalendarTimeDom(task: EsTask, index: number): VNode {
    const isShow = allowModifyPlanTimeJudgeHandler(task) && (task.planStartTimeShow || task.planEndTimeShow)
    return (
      <div class="calendar-time">
        <div>
          { task.planStartTimeShow && 
            <p class='side-item-time'>
              {i18n.t('common.form.type.planStartTime')}：{(task.planStartTime && fmt_datetime(task.planStartTime)) || '--'}
            </p>
          }
          { task.planEndTimeShow && 
            <p class='side-item-time'>
              {i18n.t('common.form.type.planEndTime')}：{(task.planEndTime && fmt_datetime(task.planEndTime)) || '--'}
            </p>
          }
        </div>
        { isShow && (
          <i class='iconfont icon-bianji1' onClick={(event: Event) => this.openPlanTimeDialog(event, task, index)}></i>
        )}
      </div>
    )
  }
  
  public renderTaskMapInfoWindowHeader(task: EsTask): VNode | null {
    
    if (!this.globalIsHaveTaskViewDetailAuth) return null;
    
    return (
      <el-button type='primary' onClick={() => allotTaskJump(task, Boolean(this.restructAllot))}>
        {i18n.t('common.task.button.allot')}
      </el-button>
    )
  }
  
  public renderAllotMapComponents(): VNode[] {
    return [
      this.renderPlantimeDialogComponent(),
      this.renderBatchAllotDialogComponent(),
      this.renderTaskMapInfoWindowComponent(),
      this.renderCalendarPlantimeDialogComponent()
    ]
  }
  
  public renderPlantimeDialogComponent(): VNode {
    return (
      <plantime-dialog 
        ref='PlanTimeDialogComponent'
        enableSendSms={false}
        task={this.currentSelectedMarkTask.data}
        field={this.currentSelectedMarkTaskPlantimeField}
        modifiable
        successCallback={(newPlanTime: string) => this.updatePlanTime(newPlanTime)} />
    )
  }

  public renderCalendarPlantimeDialogComponent(): VNode {
    return (
      <calendar-plantime-dialog
        ref='CalendarPlanTimeDialogComponent'
        enableSendSms={false}
        task={this.currentSelectedMarkTask.data}
        modifiable
        isAcceptCalendarTime={false}
        successCallback={(newCalendarPlan: object) => this.updateCalendarPlanTime(newCalendarPlan)} />
    )
  }
  
  public renderBatchAllotDialogComponent(): VNode {
    return (
      <batch-allot-dialog ref='BatchAllotDialogComponent' taskIdList={this.selectedTaskIds} taskConfig={this.taskConfig} />
    )
  }
  
  public renderTaskMapInfoWindowComponent() {
    const task: EsTask | undefined = this.currentSelectedMarkTask.data
    const taskType: TaskType | undefined = this.getTaskType(task)
    
    return (
      <div class="need-hide-in-oversize">
        <task-map-info-window
          style="min-width:320px"
          ref='TaskMapInfoWindowComponent'
          allowCustomerAuth={task?.linkAuth}
          enableSendSms={false}
          planTimeField={this.currentSelectedMarkTaskPlantimeField}
          renderTaskMapInfoWindowHeader={(taskData: EsTask) => this.renderTaskMapInfoWindowHeader(taskData)}
          show={this.visibleMapInfoWindow}
          showModifyPlanTime={this.allowModifyPlanTime}
          showCloseButton={false}
          task={task}
          taskType={taskType}
          taskConfig={this.taskConfig}
          onClose={() => this.closeInfoWindowHandler()}
          onPlanTimeChange={(planTime: string) => this.updatePlanTime(planTime)}
          onUpdateCalendarPlanTime={(newCalendarPlan: object) => this.updateCalendarPlanTime(newCalendarPlan)}
        />
      </div>
    )
  }
  
}

export default AllotMapDialogRender
